<script setup lang="tsx">
import { PropType, ref } from 'vue'
import { Descriptions, DescriptionsSchema } from '@/components/Descriptions'
import { ElTag, ElTable, ElTableColumn } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { Log } from '@/utils/logError'
import { LogPageResultItem } from '@/api/log/types'
import { getLogDetailApi } from '@/api/log'

const { t } = useI18n()

const props = defineProps({
  currentRow: {
    type: Object as PropType<LogPageResultItem | null>,
    default: () => {}
  }
})

const detailSchema = ref<DescriptionsSchema[]>([
  {
    field: 'operatorName',
    label: t('log.operatorName')
  },
  {
    field: 'operatorId',
    label: t('log.operatorId')
  },
  {
    field: 'path',
    label: t('log.path')
  },
  {
    field: 'operation',
    label: t('log.operation')
  },
  {
    field: 'ip',
    label: t('IP')
  },
  {
    field: 'isError',
    label: t('log.isError'),
    slots: {
      default: (data: any) => {
        return (
          <ElTag type={data.isError ? 'danger' : 'primary'}>
            {data.isError ? t('common.yes') : t('common.no')}
          </ElTag>
        )
      }
    }
  },
  {
    field: 'ua',
    label: t('User Agent'),
    span: 24
  },
  {
    field: 'createdAt',
    label: t('common.createTime'),
    span: 24
  },
  {
    field: 'content',
    label: t('log.content'),
    span: 24,
    slots: {
      default: function (data: any) {
        const content = Object.entries(data.content || {}).map(([key, value]) => ({
          key,
          value
        }))
        return (
          <ElTable data={content || []}>
            <ElTableColumn prop="key" label="Key" />
            <ElTableColumn
              prop="value"
              label="Value"
              v-slots={{
                default: ({ row }) =>
                  typeof row.value === 'object' ? (
                    <pre style={{ margin: 0, fontFamily: 'inherit' }}>
                      {JSON.stringify(row.value, null, 2)}
                    </pre>
                  ) : (
                    row.value
                  )
              }}
            />
          </ElTable>
        )
      }
    }
  }
])

const departmentDetailData = ref()

const getLogDetail = async () => {
  try {
    const { requestId } = props.currentRow || {}
    if (!requestId) return (departmentDetailData.value = {})
    const res = await getLogDetailApi(requestId)
    departmentDetailData.value = res.data || {}
  } catch (error) {
    Log.error('getLogDetail', error)
  }
}
getLogDetail()
</script>

<template>
  <Descriptions :schema="detailSchema" :data="departmentDetailData || {}" />
</template>
